【问题标题】:Change whole rvalue array更改整个右值数组
【发布时间】:2021-05-07 20:07:07
【问题描述】:

我想在构造函数中传递几个整数并像这样更改结构的字段:

struct testStruct
{
  testStruct(int argIntArray[])
  {
    intArray = argIntArray;
  }

  int intArray[5];
};

void main()
{
  testStruct test1(new int[5]{1,2,3,4,3});
}

但我不能那样做。 intArray = argIntArray; = "表达式必须是可修改的左值"。我可以像 intArray[0] = argIntArray[0]; 那样做,但这不是一个优雅的解决方案。

我知道我可以用指针表示法做到这一点,但有没有办法用数组表示法做到这一点?

【问题讨论】:

  • 这是std::arraystd::vector 优于数组的众多原因之一。
  • 使用std::copy() 来做到这一点
  • @AlexanderZolkin 另外,您的解决方案一开始并不是很优雅,因为new int[5]{1,2,3,4,3} 是内存泄漏,因为您从不使用delete[] 数组。也许std::initializer_list 更适合你? testStruct(std::initializer_list<int> argInts) ... testStruct test1({1,2,3,4,3});
  • intArray = argIntArray; 是错误的。复制条目。
  • A.只是不要在 C++ 中使用 C 数组,而是使用 std::array 或 std::vector ,并使用 std::span 来引用内存中任意连续的数据列表(gsl::span 可以在 C++ 之前使用20); B. C 数组是 C(然后是 C++)中的二等公民。像函数一样,它们可以被声明,但是一旦你使用它们,它们就会衰减为指向它们的第一个元素的指针(即 &a[0])。它们不能按值传递或引用,并且它们具有超级不稳定的语义(C++ 允许像T (&)[N] 这样的东西根本没有帮助)。远离他们,你的生活会更轻松。

标签: c++ arrays pointers


【解决方案1】:

考虑到我的局限性(我只能使用 C 函数),memmove() 可以解决问题:

#include <cstring>

const unsigned int markArraySize = 5;

struct TestStruct
{
  TestStruct(int argIntArray[])
  {
    memmove(intArray, argIntArray, sizeof(int)*markArraySize);
  }

  int intArray[markArraySize];
};

int main()
{
  int testArray[5] = {1, 9, 3, 4, 3};
  TestStruct testStruct(testArray);
  return 0;
}

加法。

我还发现了如何在没有像 memmove() 这样的额外功能的情况下做到这一点:

#include <iostream>

void testFunc(const int (&array)[5])
{
  std::cout << array[0] << std::endl;
}

int main()
{
  testFunc({1, 2, 3, 4, 5});

  return 0;
}

【讨论】:

    猜你喜欢
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 2020-02-06
    • 2018-06-15
    相关资源
    最近更新 更多