关于实现(编译器)不提供复制构造函数和复制赋值运算符的情况,我有一点混淆.
我对第二种情况有点困惑,第二种情况正是如此.
a)实现不会为您声明它们,因此您将收到编译时错误.
或者
b)实现将声明并定义它们,但是当编译器定义的实现试图找到基类的方法时,我们将得到编译时错误.
昨天我接受了一次采访,我说(b)正在发生,但面试官不同意,他说(a).
我尝试在Microsoft C/C++ 14.00和gcc 4.4.5中编译以下代码
struct A
{
private:
A& operator = ( const A& );
};
struct B : A
{
};
int main()
{
B b1;
B b2;
b1 = b2;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Microsoft编译器输出
ctor01.cpp(9) : error C2248: 'A::operator =' : cannot access private member declared in class 'A'
ctor01.cpp(4) : see declaration of 'A::operator ='
ctor01.cpp(2) : see declaration of 'A'
This diagnostic occurred in the compiler generated function …Run Code Online (Sandbox Code Playgroud) 这些是我的原型,
MyClass& operator=(MyClass rhs); // copy assignment
MyClass& operator=(MyClass &&rhs); // move assignment
Run Code Online (Sandbox Code Playgroud)
但是当我打电话时
MyClass a, b;
a = std::move(b);
Run Code Online (Sandbox Code Playgroud)
,有一个错误.
556 IntelliSense: more than one operator "=" matches these operands:
function "MyClass::operator=(MyClass rhs)"
function "MyClass::operator=(MyClass &&rhs)"
operand types are: MyClass = MyClass
Run Code Online (Sandbox Code Playgroud)
并且编译器返回:
Error 56 error C2593: 'operator =' is ambiguous
Run Code Online (Sandbox Code Playgroud) 我正在为我创建的一个类编写一个复制赋值运算符,我使用以前的帖子作为指导: 什么是三法则?
我对这个人解释的一个方面有点困惑。
这是他们的课:
class person
{
char* name;
int age;
};
Run Code Online (Sandbox Code Playgroud)
这是我用作参考的复制赋值运算符定义(至少提供了 2 个):
// 2. copy assignment operator
person& operator=(const person& that)
{
char* local_name = new char[strlen(that.name) + 1];
// If the above statement throws,
// the object is still in the same state as before.
// None of the following statements will throw an exception :)
strcpy(local_name, that.name);
delete[] name;
name = local_name;
age = that.age;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
我发现令人困惑的是,为什么他们包括这条线delete[] name;?
这是他们提供的另一个示例:
person& operator=(const …Run Code Online (Sandbox Code Playgroud) 例如,我想要做的深层复制a到b:
>> a=zeros(2,3);
>> b=a;
Run Code Online (Sandbox Code Playgroud)
所以这里=只创建了一个浅拷贝。我的问题是,在这种情况下如何生成深拷贝?我知道我可以添加一个命令
b(1,1)=b(1,1)
Run Code Online (Sandbox Code Playgroud)
使其成为深拷贝。但是有没有更好的方法来做到这一点?
我喜欢std :: unique_ptr.它帮助我防止内存泄漏,这是非常有用的.但是有一个问题:不允许复制分配和构造.
即使这种限制有助于程序员的安全,但它也是非常有限的.如果使用std :: unique_ptr作为其成员使用复制赋值和构造的类,则最终会出现问题.这就是为什么我使用复制构造和赋值创建了我自己的unique_ptr包装器.这是它的复制构造函数:
template<typename T, class Deleter>
PointerSmartSafe<T, Deleter>::PointerSmartSafe(PointerSmartSafe const& pointer_smart_safe_) noexcept : _m_opPointerUnique((_m_opPointerUnique == nullptr) ? new T(*_m_opPointerUnique.get()) : nullptr){
}
Run Code Online (Sandbox Code Playgroud)
这是复制赋值运算符:
template<typename T, class Deleter>
PointerSmartSafe<T, Deleter>& PointerSmartSafe<T, Deleter>::operator=(PointerSmartSafe const& pointer_smart_safe_) noexcept{
_m_opPointerUnique = decltype(_m_opPointerUnique)(new T(*_m_opPointerUnique.get()));
return *this;
}
Run Code Online (Sandbox Code Playgroud)
一切正常,直到我最终使用抽象基类作为类型(T).我收到如下错误消息:
error: cannot allocate an object of abstract type 'AbstractBaseClass'
Run Code Online (Sandbox Code Playgroud)
这让我感到困惑.是否存在变通方法?
类似问题:
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<vector<int> > vvi;
vvi.resize(1);
vvi[0].reserve(1);
vvi[0][0] = 1;
vector<int> vi = vvi[0];
cout << vi[0]; // cout << vvi[0][0]; works
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这给了我一个段错误,我不知道为什么.
我有一个2D数组A形状(4,3)和一维a形状的数组(4,).我想交换前两行A,以及前两行中的元素a.我做了以下事情:
A[0,:],A[1,:] = A[1,:],A[0,:]
a[0],a[1] = a[1],a[0]
Run Code Online (Sandbox Code Playgroud)
显然,它适用于a,但失败了A.现在,第二行成为第一行,但第一行保持不变.如果我执行以下操作:
first_row_copy = A[0,:].copy()
A[0,:] = A[1,:]
A[1,:] = first_row_copy
Run Code Online (Sandbox Code Playgroud)
然后,它似乎工作.为什么第一种方法不起作用?(但适用于a)另外,A_copy = A[0,:].copy()和之间的区别是A_copy = A[0,:]什么?
这是一个实现"三个规则"的例子,我发现:
class Array {
public:
int size;
int* vals;
Array() : size(0), vals(NULL){}
Array( int s, int* v );
Array(const Array&); // 1
Array& operator=(const Array&); // 2
~Array(); // 3
};
Array::~Array() {
delete []vals;
vals = NULL;
}
Array::Array( int s, int* v ){
size = s;
vals = new int[size];
std::copy( v, v + size, vals );
}
Array::Array(const Array& rhs):
size(rhs.size),
vals((rhs.size) ? new int[size] : NULL)
{
if(size)
std::copy(rhs.vals, rhs.vals + rhs.size, vals);
}
Array& …Run Code Online (Sandbox Code Playgroud) 我正在对来自 numpy 数组的标量值进行一些快速计算。正如文档中所说,
使用数组标量的主要优点是它们保留了数组类型(Python 可能没有可用的匹配标量类型,例如 int16)...
但是有没有比这更好(更快,更简洁)的方法来为现有数组标量分配一个新值:
>>> x = np.array(2.0, dtype='float32')
Run Code Online (Sandbox Code Playgroud)
这有效但不是那么方便(我正在做其他算术并希望始终保留该类型)。
由于明显的原因,这不起作用:
>>> x = np.array(1.0, dtype='float32')
>>> print(x, type(x))
1.0 <class 'numpy.ndarray'>
>>> x = 2.0
>>> print(x, type(x))
2.0 <class 'float'>
Run Code Online (Sandbox Code Playgroud)
这也不行:
>>> x = np.array(1.0, dtype='float32')
>>> x[] = 2.0
File "<ipython-input-319-7f36071ff81d>", line 2
x[] = 2.0
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
也不是这个:
>>> x = np.array(1.0, dtype='float32')
>>> x[:] = 2.0
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-24-62cd4ca238ce> in <module>()
1 x …Run Code Online (Sandbox Code Playgroud) 我必须用来malloc分配内存.我有一个需要自定义的自定义类operator=.让我们说它是A:
class A {
public:
int n;
A(int n) : n(n) {}
A& operator=(const A& other) {
n = other.n;
return *this;
}
};
Run Code Online (Sandbox Code Playgroud)
我分配内存malloc:
int main() {
A* a = (A*) malloc(sizeof(A));
A b(1);
//Is it safe to do this as long as I copy everything in operator=?
*a = b;
//Clean up
a->~A();
free(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我知道我也可以使用新的位置:
a = new (a) A(b);
Run Code Online (Sandbox Code Playgroud)
将自定义类复制到未初始化的内存是否安全?
谢谢
我按照三个规则实施了一个类,我遇到了崩溃.在调试时,我得出结论,复制构造函数反复调用自身而不是调用相等运算符.为什么会这样?它不应该调用相等运算符吗?
#include <iostream>
#include <deque>
#include <cstdlib>
#define LENGTH 128
typedef struct tDataStruct
{
char strA[LENGTH];
char strB[LENGTH];
int nNumberOfSignals;
double* oQueue;
tDataStruct()
{
nNumberOfSignals = 0;
//oQueue = NULL;
memset(strA, 0, LENGTH);
memset(strB, 0, LENGTH);
}
~tDataStruct()
{
if (NULL != oQueue)
{
delete[] oQueue;
oQueue = NULL;
}
}
tDataStruct(const tDataStruct& other) // copy constructor
{
if (this != &other)
{
*this = other;
}
}
tDataStruct& operator=(tDataStruct other) // copy assignment
{
if (this == &other)
{ …Run Code Online (Sandbox Code Playgroud) 根据我的情况1使用复制赋值运算符,因此输出应该是0 68但0 87在情况2中它87 87是正常的.
#include <iostream>
using namespace std;
class numbered
{
static int un;
public:
int a;
numbered (): a(un) {un++;}
numbered(const numbered & n) : a(87){}
numbered & operator=(const numbered) { a=68; return *this; }
};
int numbered::un=0;
void f(numbered s){ cout<<s.a;}
int main()
{
numbered a, b=a;
cout << a.a << b.a; //case 1
f(a);f(b); //case 2
return 0;
}
Run Code Online (Sandbox Code Playgroud) copy-assignment ×12
c++ ×9
arrays ×2
numpy ×2
python ×2
c++11 ×1
class ×1
copy ×1
deep-copy ×1
matlab ×1
noncopyable ×1
scalar ×1
shallow-copy ×1
stdvector ×1
unique-ptr ×1