assignment operator(=) for vector demo

本文介绍了一个简单的C++程序示例,演示了如何使用标准模板库(STL)中的向量容器存储整数并进行遍历输出。通过这个例子,读者可以了解向量的基本用法以及范围for循环的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> ivec;
    ivec = {1, 2, 3, 4, 5};

    for (auto val : ivec) {
        cout << val << " ";
    }
    cout << endl;

    return 0;
}

uo@guo-Dell-G15-5520:~/g2o仿真/src/build$ make Consolidate compiler generated dependencies of target g2o_demo [ 50%] Building CXX object CMakeFiles/g2o_demo.dir/optimize.cc.o In file included from /usr/local/include/eigen3/Eigen/Core:164, from /opt/ros/noetic/include/g2o/core/eigen_types.h:30, from /opt/ros/noetic/include/g2o/config.h:45, from /opt/ros/noetic/include/g2o/core/openmp_mutex.h:30, from /opt/ros/noetic/include/g2o/core/optimizable_graph.h:34, from /opt/ros/noetic/include/g2o/core/base_vertex.h:30, from /home/guo/g2o仿真/src/optimize.cc:4: /usr/local/include/eigen3/Eigen/src/Core/AssignEvaluator.h: In instantiation of ‘void Eigen::internal::call_assignment_no_alias(Dst&, const Src&, const Func&) [with Dst = Eigen::Matrix<double, 6, 1, 0, 6, 1>; Src = Eigen::Matrix<double, 3, 1>; Func = Eigen::internal::assign_op<double, double>]’: /usr/local/include/eigen3/Eigen/src/Core/PlainObjectBase.h:797:41: required from ‘Derived& Eigen::PlainObjectBase<Derived>::_set_noalias(const Eigen::DenseBase<OtherDerived>&) [with OtherDerived = Eigen::Matrix<double, 3, 1>; Derived = Eigen::Matrix<double, 6, 1, 0, 6, 1>]’ /usr/local/include/eigen3/Eigen/src/Core/PlainObjectBase.h:594:7: required from ‘Eigen::PlainObjectBase<Derived>::PlainObjectBase(const Eigen::DenseBase<OtherDerived>&) [with OtherDerived = Eigen::Matrix<double, 3, 1>; Derived = Eigen::Matrix<double, 6, 1, 0, 6, 1>]’ /usr/local/include/eigen3/Eigen/src/Core/Matrix.h:423:29: required from ‘Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::Matrix(const Eigen::EigenBase<OtherDerived>&) [with OtherDerived = Eigen::Matrix<double, 3, 1>; _Scalar = double; int _Rows = 6; int _Cols = 1; int _Options = 0; int _MaxRows = 6; int _MaxCols = 1]’ /home/guo/g2o仿真/src/optimize.cc:43:68: required from here /usr/local/include/eigen3/Eigen/src/Core/util/StaticAssert.h:177:5: error: static assertion failed: YOU_MIXED_MATRICES_OF_DIFFERENT_SIZES 175 | ( \ | ~~~ 176 | (int(Eigen::internal::size_of_xpr_at_compile_time<TYPE0>::ret)==0 && int(Eigen::internal::size_of_xpr_at_compile_time<TYPE1>::ret)==0) \ | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 177 | || (\ | ^~~~~ 178 | (int(TYPE0::RowsAtCompileTime)==Eigen::Dynamic \ | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 179 | || int(TYPE1::RowsAtCompileTime)==Eigen::Dynamic \ | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 180 | || int(TYPE0::RowsAtCompileTime)==int(TYPE1::RowsAtCompileTime)) \ | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 181 | && (int(TYPE0::ColsAtCompileTime)==Eigen::Dynamic \ | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 182 | || int(TYPE1::ColsAtCompileTime)==Eigen::Dynamic \ | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 183 | || int(TYPE0::ColsAtCompileTime)==int(TYPE1::ColsAtCompileTime))\ | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 184 | ) \ | ~~~ 185 | ) | ~ /usr/local/include/eigen3/Eigen/src/Core/util/StaticAssert.h:33:54: note: in definition of macro ‘EIGEN_STATIC_ASSERT’ 33 | #define EIGEN_STATIC_ASSERT(X,MSG) static_assert(X,#MSG); | ^ /usr/local/include/eigen3/Eigen/src/Core/util/StaticAssert.h:194:6: note: in expansion of macro ‘EIGEN_PREDICATE_SAME_MATRIX_SIZE’ 194 | EIGEN_PREDICATE_SAME_MATRIX_SIZE(TYPE0,TYPE1),\ | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /usr/local/include/eigen3/Eigen/src/Core/AssignEvaluator.h:887:3: note: in expansion of macro ‘EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE’ 887 | EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(ActualDstTypeCleaned,Src) | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ make[2]: *** [CMakeFiles/g2o_demo.dir/build.make:76:CMakeFiles/g2o_demo.dir/optimize.cc.o] 错误 1 make[1]: *** [CMakeFiles/Makefile2:673:CMakeFiles/g2o_demo.dir/all] 错误 2 make: *** [Makefile:146:all] 错误 2 guo@guo-Dell-G15-5520:~/g2o仿真/src/build$
最新发布
08-03
### 关于编程中的 `operator=` 使用或错误 `operator=` 是 C++ 中的一个特殊成员函数,用于实现对象赋值操作。它允许开发者定义如何将一个对象的内容复制到另一个对象中。如果未显式定义该运算符,则编译器会自动生成默认版本[^3]。 #### 默认行为 当类没有提供自己的 `operator=` 实现时,C++ 编译器会生成一个默认的拷贝赋值运算符。这个默认版本逐成员地执行浅拷贝(shallow copy)。这意味着对于指针类型的成员变量,仅复制其地址而非实际数据内容[^4]。 ```cpp class MyClass { public: int* ptr; // Default constructor MyClass() : ptr(new int(0)) {} ~MyClass() { delete ptr; } }; // Example of shallow copying leading to undefined behavior. void testDefaultAssignmentOperator() { MyClass obj1; *obj1.ptr = 10; MyClass obj2; obj2 = obj1; // Uses default assignment operator std::cout << "*obj2.ptr: " << *obj2.ptr << "\n"; // Outputs 10 // Both objects now point to same memory location after destruction leads to double-free error } ``` 上述代码展示了由于使用默认赋值运算符而导致的双重释放问题[^5]。 #### 自定义 `operator=` 为了避免潜在的风险,在某些情况下需要重载 `operator=` 来实施深拷贝(deep copy),即创建新内存并复制原始数据至其中: ```cpp class MyClassWithDeepCopy { private: int* data; public: explicit MyClassWithDeepCopy(int value) : data(new int(value)) {} ~MyClassWithDeepCopy() { delete data; } // Copy Assignment Operator Overload using copy-and-swap idiom MyClassWithDeepCopy& operator=(const MyClassWithDeepCopy& other) { auto temp = new int(*other.data); swap(data, temp); delete temp; return *this; } }; ``` 此方法遵循了 **copy-and-swap** 范式来确保强异常安全性以及自我赋值的安全处理[^6]。 #### 常见错误及其解决方案 以下是几个常见的关于 `operator=` 的误用场景及对应的修正措施: 1. **忽略返回类型** 如果忘记让 `operator=` 返回当前实例 (`return *this`) ,则链式调用将会失效。 2. **缺乏对自赋值的支持** 当目标和源是同一个对象时可能发生意外情况;因此应始终考虑这种情况下的正确性保障。 3. **资源泄漏风险** 对动态分配的数据结构进行管理不当容易引发内存泄露等问题,故需谨慎对待每一步骤以防止此类隐患发生。 #### 并发环境下的注意事项 在多线程环境中应用 `operator=` 可能面临额外挑战。例如,两个不同线程可能同时尝试修改同一共享状态的对象副本。此时应当引入同步机制保护关键区域免受竞争条件影响[^7]: ```cpp std::mutex mtx; class ThreadSafeObject { protected: mutable std::mutex m_mutex; int value_; public: ThreadSafeObject(const ThreadSafeObject &rhs) noexcept(false){ std::lock_guard<std::mutex> lock(rhs.m_mutex); this->value_ = rhs.value_; }; ThreadSafeObject& operator=(ThreadSafeObject const& other) { if(this != &other){ std::unique_lock<std::mutex> lhsLock(m_mutex,std::defer_lock), rhsLock(other.m_mutex,std::defer_lock); std::lock(lhsLock,rhsLock); // Avoid deadlock value_=other.value_; } return *this; }; }; ``` 通过以上方式可以有效减少因并发访问带来的不确定性因素干扰程序正常运行流程的可能性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值