小编JVA*_*pen的帖子

在什么情况下我使用malloc vs new?

我在C++中看到有多种方式来分配和释放数据,我知道当你打电话给malloc你时应该打电话free,当你使用new操作员时你应该配对,delete将两者混合是错误的(例如,调用free()创建的东西)与new操作员),但我不知道何时应该使用malloc/ free何时应该在我的真实世界程序中使用new/ delete.

如果您是C++专家,请告诉我您在此方面遵循的任何经验法则或惯例.

c++ malloc memory-management new-operator

447
推荐指数
12
解决办法
26万
查看次数

C ++ 20是否要求将源代码存储在文件中?

但是,一个有点奇怪的问题是,如果我没有记错的话,C ++源代码不需要文件系统来存储其文件。

拥有一个可以通过照相机扫描手写纸的编译器将是一个符合要求的实现。尽管实际上没有太大意义。

但是,C ++ 20现在使用添加了源位置file_name。现在,这是否意味着源代码应始终存储在文件中?

c++ language-lawyer c++20 std-source-location

103
推荐指数
2
解决办法
1万
查看次数

使用 std::type_info 在 natvis 中进行转换

在我正在工作的代码库中,我们使用std::any而不是void*通过一些通用的非模板代码来传递类。具体来说,我们使用 Visual Studio 2019、它的编译器和标准库。

为了可视化std::any,微软已经给出了一个natvis:

  <Type Name="std::any">
      <Intrinsic Name="has_value"   Expression="_Storage._TypeData != 0"/>
      <Intrinsic Name="_Rep"        Expression="_Storage._TypeData &amp; _Rep_mask"/>
      <Intrinsic Name="type"        Expression="(const type_info*)(_Storage._TypeData &amp; ~_Rep_mask)"/>
      <Intrinsic Name="_Is_trivial" Expression="has_value() &amp;&amp; _Rep() == 0"/>
      <Intrinsic Name="_Is_big"     Expression="has_value() &amp;&amp; _Rep() == 1"/>
      <Intrinsic Name="_Is_small"   Expression="has_value() &amp;&amp; _Rep() == 2"/>
      <DisplayString Condition="!has_value()">[empty]</DisplayString>
      <DisplayString Condition="_Is_trivial() || _Is_small()">[not empty (Small)]</DisplayString>
      <DisplayString Condition="_Is_big()">[not empty (Large)]</DisplayString>
      <Expand>
          <Synthetic Name="has_value">
              <DisplayString>{has_value()}</DisplayString>
          </Synthetic>
          <Synthetic Name="type" Condition="has_value()">
              <DisplayString>{type()}</DisplayString>
          </Synthetic>
          <Synthetic Name="[representation]" Condition="_Is_trivial()">
              <DisplayString>(Small/Trivial Object)</DisplayString>
          </Synthetic>
          <Synthetic Name="[representation]" …
Run Code Online (Sandbox Code Playgroud)

c++ visual-studio natvis c++17

15
推荐指数
1
解决办法
926
查看次数

将用户角色添加到jwt,laravel 5 jwt-auth

我有一个laravel 5后端,使用jwt-auth在登录时发送jwt-token作为json响应.

现在我想将用户角色添加到laravel发送的jwt令牌中,我尝试了以下方式:

这是我现在的控制器

<?php 
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Database\Eloquent\Model;
use App\User;

class AuthenticateController extends Controller
{
    public function authenticate(Request $request)
    {
        // grab credentials from the request
        $credentials = $request->only('email', 'password');
        $user = User::where('email', '=', $credentials['email'])->first();
        $customClaims = ['role' => $user->role];

        try {
            // attempt to verify the credentials and create a token for the user
            if (! $token = JWTAuth::attempt($credentials, $customClaims)) {
                return response()->json(['error' => 'invalid_credentials'], 401);
            }
        } …
Run Code Online (Sandbox Code Playgroud)

php jwt laravel

14
推荐指数
1
解决办法
7584
查看次数

[[maybe_unused]]在枚举器上

看一下规范[[maybe_unused]],它说:

出现在类,typedef,变量,非静态数据成员,函数,枚举或枚举器的声明中.如果编译器对未使用的实体发出警告,则对于声明为maybe_unused的任何实体,将禁止该警告.

由于这提到了调查员,我有点期望它有一个用例.我唯一想到的就是-Wswitch警告,我和Clang,GCC和MSVC一起尝试过.

enum A
{
    B,
    C [[maybe_unused]]
};

void f(A a)
{
    switch (a)
    {
        case B: break;
    }
}
Run Code Online (Sandbox Code Playgroud)

所有3个编译器都给出了以下警告的变体:

<source>:9:13: warning: enumeration value 'C' not handled in switch [-Wswitch]
    switch (a)
            ^
Run Code Online (Sandbox Code Playgroud)

实时代码

这是使用此属性的有效用例吗?是否有其他用例在此位置添加属性或者这只是一个无用的添加?

c++ attributes language-lawyer c++17

10
推荐指数
2
解决办法
272
查看次数

如何在 Visual Studio 中使用 clang-format

自 15.7 prev1 起, Visual Studio 就对 clang-format 进行了本机集成

我使用的是 15.9.9,可以很好地看到选项中的配置。 Visual Studio 配置 C++ 格式

根据我的理解,由于在格式样式中选择了“Google”,因此它应该使用位于结账根目录中的 .clang 格式文件,或者回退到名为“Google”的硬编码配置。

但是,如果我格式化文件:Ctrl+K、Ctrl+D,我的文件将使用 Whitesmiths 进行格式化;这是我的 Visual Studio 格式的大括号配置。

我是否忘记配置一些允许我使用 clang-format 的东西,或者出现了严重的错误?如果是最后一个,我很欣赏一些调试技巧。

c++ visual-studio clang-format visual-studio-2017

10
推荐指数
1
解决办法
3万
查看次数

浮点运算是否导致IEC 559 / IEEE 754浮点类型的无限不确定行为

我正在阅读Infinity而不是constexpr,这似乎表明创建Infinity是未定义的行为:

[expr] / 4

如果在表达式的求值过程中,未在数学上定义结果或该类型的结果不在可表示值的范围内,则行为不确定。

但是,如果std::numeric_limits::is_iec559 等于true,则似乎为我们提供了更多保证。

下面的代码利用此保证来创建无限数。在constexpr上下文中执行时,会导致编译器失败,因为undefined behavior如果情况为is_iec559假,则失败。

// clang++ -std=c++17 -O3
#include <limits>

constexpr double createInfinity()
{
    static_assert(std::numeric_limits<double>::is_iec559, "asdf");
    double d = 999999999999;
    while (d != std::numeric_limits<double>::infinity())
    {
        d *= d;
    }
    return -1*d;
}

static_assert(createInfinity() == std::numeric_limits<double>::infinity(), "inf");
Run Code Online (Sandbox Code Playgroud)

编译器资源管理器中的代码

由于此函数总是导致无限,因此永远不能在有效的C ++程序中调用它。但是,正如我们对所断言的那样is_iec559,我们获得了额外的保证。该程序仍然无效吗?

  • 如果无效?有什么意义is_iec559
  • 是否有效?为什么在运行时有效,而不在constexpr上下文中有效?

(答案可以同时使用C ++ 17和即将推出的C ++ 20,请清楚说明使用的是哪种)

c++ floating-point language-lawyer c++17 c++20

10
推荐指数
1
解决办法
231
查看次数

为什么在 C++17 中复制初始化需要析构函数并保证移动/复制省略?

以下代码使用 MSVC (/permissive-) 编译,但无法使用 GCC/Clang 编译 m_ptr1 和 m_ptr2。

#include <memory>

struct ForwardDeclared;

class A {
    public:
        explicit A();
        ~A();
    private:
        std::unique_ptr<ForwardDeclared> m_ptr1 = nullptr;    // not ok
        std::unique_ptr<ForwardDeclared> m_ptr2 {std::unique_ptr<ForwardDeclared>{}};    // not ok
        std::unique_ptr<ForwardDeclared> m_ptr3 {nullptr};    // ok 
        std::unique_ptr<ForwardDeclared> m_ptr4;              // ok
};

int main() {
    A a;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器资源管理器中的代码

我的理解是该=符号会导致复制初始化,但是,由于复制省略,我预计m_ptr2仍会被初始化而不会失败。

为什么m_ptr2需要 ForwardDeclared 的析构函数并且 Clang/GCC 对此是否正确?(奖励:得出 m_ptr1 被 MSVC 错误接受的结论是否正确?)

c++ language-lawyer copy-initialization copy-elision c++17

10
推荐指数
1
解决办法
229
查看次数

为什么接受默认的 noexcept 移动构造函数?

假设以下 c++17 代码:

#include <type_traits>
namespace dtl
{
   struct One
   {
      explicit One(int);
      ~One() = default;
      One(const One &) = delete;
      auto operator=(const One &) -> One & = delete;
      auto operator=(One &&) -> One & = delete;
      One(One &&); // Throwable, not default;
      int m_int;
   };
   struct Two 
   {
      explicit Two(int);
      ~Two() = default;
      Two(const Two &) = delete;
      auto operator=(const Two &) -> Two & = delete;
      auto operator=(Two &&) noexcept -> Two & = delete;
      Two(Two &&) …
Run Code Online (Sandbox Code Playgroud)

c++ default-constructor language-lawyer noexcept c++17

8
推荐指数
1
解决办法
303
查看次数

参考同一向量的数据插入向量

我目前处于一种情况,我想复制一个向量中的一些元素.简而言之,我的代码类似于以下内容:

std::vector<MyStruct> v;
// ...
auto toDuplicate = std::find(v.begin(), v.end(), [](const MyStruct &s) { return true; /*In reality, a bit more complex*/ });
v.insert(toDuplicate, nrOfDuplicates-1, *toDuplicate);
// Signature: insert(iterator, size_t, const value_type &)
Run Code Online (Sandbox Code Playgroud)

因此,在这种情况下,如果容量小于最终容量,则std :: vector必须重新分配其内部数据,使得我的引用插入的数据无效.

我正在使用的STL(MSVC2013)的实现包含对这种插入的保护,因为如果需要重新分配它将执行我的元素的副本.但是,我不确定我是否能够依赖这种行为,还是需要我自己先复制一份?(当我升级到新的STL实现时,我宁愿防止自己看到这种错误)

所以简而言之:我是否允许在向量上调用insert()并引用同一向量中的元素?

c++ stl vector stdvector

7
推荐指数
1
解决办法
128
查看次数