当将STL容器复制到自身中时

当将STL容器复制到自身中时

本文介绍了当将STL容器复制到自身中时,STL容器是否应避免将元素复制到自身中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题在于自我分配.例如,将向量复制到自身中:

The question is about self-assignment. For example copying a vector into itself:

std::vector<std::string> vec(5, "hello");
vec = vec;

上面的代码应该对自己执行5个字符串赋值操作,还是什么都不做?我的意思是以下检查是否有效:

Should the code above perform 5 assignment operations of strings into themselves, or just do nothing? I mean whether the following checking is valid:

std::vector operator=(const std::vector &rhs)
{
    if (this == &rhs)
        { return *this; }
    ...
}

我正在开发自己的std::variant类的实现(只是为了好玩),并且对我是否应该在自赋值运算符的开头添加自赋值检查感兴趣,还是应该将包含的元素复制到自身中而感兴趣?

I'm working on my own implementation of std::variant class (just for fun) and interested if I should add a self-assignment check to the beginning of the assignment operator, or should I just copy the contained element into itself?

我知道通常这并不重要.您不应该创建一个利用复制本身的事实的类.但是我很想知道标准是否对此有所说明.

I understand that generally this doesn't matter. You should not make a class that utilizes the fact of copying into itself. But I'm interested if the standard says anything about this.

推荐答案

由标准指定的容器分配的前提条件(引用最新草案):

The pre/post conditions of assignment of a container specified by the standard (quoting latest draft):

r = a

确保:r == a.

这允许但不强制执行自我分配检查.

This allows but does not mandate self assignment check.

这篇关于当将STL容器复制到自身中时,STL容器是否应避免将元素复制到自身中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 21:14